package com.ymttest.business.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;

import com.ymatou.iapi.m.couponservice.parameter.CreateCouponBean;
import com.ymatou.iapi.m.couponservice.service.CreateCouponCall;
import com.ymatou.iapi.trading.operate.parameter.CancelOrderBean;
import com.ymatou.iapi.trading.operate.parameter.MarkOrderDeletedBean;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderResp;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderService;
import com.ymatou.iapi.trading.operate.parameter.YmatouCouponVo;
import com.ymatou.iapi.trading.operate.parameter.enums.TerminalSourceEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.YmatouCouponApplianceTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.req.AcceptOrderBean;
import com.ymatou.iapi.trading.operate.parameter.req.ApplyForPostPayBean;
import com.ymatou.iapi.trading.operate.parameter.req.ApplySalesRefundRequestBean;
import com.ymatou.iapi.trading.operate.parameter.req.ApproveRefundBillReq;
import com.ymatou.iapi.trading.operate.parameter.req.CancelPostPayBean;
import com.ymatou.iapi.trading.operate.parameter.req.ChangeOrderDiscountBean;
import com.ymatou.iapi.trading.operate.parameter.req.ConfirmReceiveBean;
import com.ymatou.iapi.trading.operate.parameter.req.DelayReceiveReqBean;
import com.ymatou.iapi.trading.operate.parameter.req.DispatchedBean;
import com.ymatou.iapi.trading.operate.parameter.req.MarkOrderLockReq;
import com.ymatou.iapi.trading.operate.parameter.req.OrderPostPayRequestBean;
import com.ymatou.iapi.trading.operate.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.trading.operate.parameter.req.RejectRefundBillReq;
import com.ymatou.iapi.trading.operate.parameter.req.SalesRefundInfoBean;
import com.ymatou.iapi.trading.operate.service.AcceptOrderCall;
import com.ymatou.iapi.trading.operate.service.ApplyForPostPayCall;
import com.ymatou.iapi.trading.operate.service.ApplySalesRefundRequestCall;
import com.ymatou.iapi.trading.operate.service.CancelOrderCall;
import com.ymatou.iapi.trading.operate.service.CancelPostPayCall;
import com.ymatou.iapi.trading.operate.service.ChangeOrderDiscountCall;
import com.ymatou.iapi.trading.operate.service.ConfirmReceiveCall;
import com.ymatou.iapi.trading.operate.service.DelayReceiveCall;
import com.ymatou.iapi.trading.operate.service.DispatchedCall;
import com.ymatou.iapi.trading.operate.service.MarkOrderDeletedCall;
import com.ymatou.iapi.trading.operate.service.MarkOrderLockCall;
import com.ymatou.iapi.trading.operate.service.OrderPostPayRequestCall;
import com.ymatou.iapi.trading.operate.service.PlaceOrderCall;
import com.ymatou.iapi.trading.operate.service.SalesRefundFailRequestCall;
import com.ymatou.iapi.trading.operate.service.SalesRefundSuccessRequestCall;
import com.ymatou.iapi.userregister.parameter.UserRegisterInfoRequestDtoBean;
import com.ymatou.iapi.userregister.service.UserRegisterInfoRequestDtoCall;
import com.ymatou.iapi.userservice.parameter.AddressRequestDtoBean;
import com.ymatou.operate.trading.api.parameter.BatchAcceptOrderBean;
import com.ymatou.operate.trading.api.parameter.BatchApplyForPostPayBean;
import com.ymatou.operate.trading.api.parameter.BatchCancelOrderBean;
import com.ymatou.operate.trading.api.parameter.BatchDispatchedBean;
import com.ymatou.operate.trading.api.service.BatchAcceptOrderCall;
import com.ymatou.operate.trading.api.service.BatchApplyForPostPayCall;
import com.ymatou.operate.trading.api.service.BatchCancelOrderCall;
import com.ymatou.operate.trading.api.service.BatchDispatchedCall;
import com.ymt.core.tool.Logger;
import com.ymttest.common.entitie.ApplyPostPayInfo;
import com.ymttest.common.entitie.DispatchedInfo;
import com.ymttest.common.enums.BillTypeEnum;
import com.ymttest.common.enums.CancelOrderTypeEnum;
import com.ymttest.common.enums.PlatformEnum;
import com.ymttest.database.model.YmtCoupon;
import com.ymttest.database.model.YmtCouponBatch;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.database.sqlwapper.YmtCouponBatchWapper;
import com.ymttest.database.sqlwapper.YmtCouponWapper;
import com.ymttest.database.sqlwapper.YmtUsersWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;

/**
 * 订单服务
 */
public class OrderCallService {

	/**
	 * 用户注册
	 * 
	 * @return
	 * @throws Exception 
	 */
	public Map<String, Comparable> registerUser() throws Exception {

		UserRegisterInfoRequestDtoBean urb = JUserCallService
				.initUserRegisterInfoRequestDtoBean();
		UserRegisterInfoRequestDtoCall uc = JUserCallService
				.UserRegisterInfoRequestDtoCall(urb);

		int userId = uc.getUserid();

		//添加用户地址信息

		JUserCallService.AddressRequestDtoCall(JUserCallService
				.initAddressBean(userId));

		AccountCallService.resetAccount(
				AccountCallService.getAccountId(userId),
				new BigDecimal(999999), new BigDecimal(999999));

		// 注册用户
		Map<String, Comparable> userMap = new HashMap();

		userMap.put("userId", userId);

		return userMap;
	}
	/**
	 * 用户注册,添加默认地址，重置余额
	 * 
	 * @return userid
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public int createNewUser() throws Exception {
		// 注册用户
		UserRegisterInfoRequestDtoBean urb = JUserCallService
				.initUserRegisterInfoRequestDtoBean();
		UserRegisterInfoRequestDtoCall uc = JUserCallService
				.UserRegisterInfoRequestDtoCall(urb);

		Integer uid = uc.getUserid();
		// 添加地址
		AddressRequestDtoBean addressBean = JUserCallService
				.initAddressBean(uid);
		JUserCallService.AddressRequestDtoCall(addressBean);

		// 设置账户余额
		String aid = AccountCallServiceV2.getAccountId(uid);

		AccountCallServiceV2.resetAccount(aid, new BigDecimal("10000000"),
				BigDecimal.ZERO);

		int userId = uc.getUserid();

		return userId;
	}

	/**
	 * APP 根据user保存闪购订单
	 * 新下单服务不区别，C和M 订单。
	 * 
	 * @param Map
	 *            买家用户信息 user {userid=??,userName=??}
	 * @return 例如：{CatalogId=cbaaf223-cb52-4d24-b89a-7411a2a85ea4,
	 *         TotalPrice=404.00, OrderId=105257375, SellerId=288484,
	 *         UserId=1113, ProductId=038505f3-b515-4aac-8f0a-f0364d4d378b}
	 */
	@Deprecated
	public Map appSaveOrder(Map user) {
		Map<String, Comparable> orderMap = new HashMap();
		PlaceOrderReq placeorderBean = this.getDefaultPlaceOrderBean();
		PlaceOrderCall placeorderCall = new PlaceOrderCall();
		try {
			/*** 读取测试数据 ***/
			int userId = (Integer) user.get("userid");
			// String buyUserName = (String) user.get("username");
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			String sellerName = EnvSetup.getData("BuyerName");
			// 买手登录
			Map m = AuthCallService.authLogin(sellerName, "123456");
			String sellerAccessToken = (String) m.get("accessToken");
			/*** 创建直播商品 ***/
			Map productinfomap = ProductCallService.createC2CProduct(
					sellerAccessToken, 1);
			/*** 获取产品信息 ***/
			String productId = (String) (productinfomap.get("productId"));
			String catalogId = (String) productinfomap.get("catalogId");
			Logger.debug("catalogId:" + catalogId);
			if (catalogId == null)
				catalogId = TestDataManager.getRandomUUID().toString();
			int activityId = (Integer) productinfomap.get("activityId");
			String picUrl = String.valueOf(productinfomap.get("pic"));
			String productName = String.valueOf(productinfomap
					.get("productDesc"));
			BigDecimal price = (BigDecimal) productinfomap.get("price");
			// 买家用户id
			placeorderBean.setUserId(userId);
			// 商家用id
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 规格id
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setCatalogId(catalogId);
			// 商品id
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductId(productId);
			// 商品图片
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setPictureUrl(picUrl);
			// 商品名称
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductName(productName);
			// 设置买手
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 商品价格
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductPrice(price);
			// 商品预付定金价 C端为商品价格的30%
			BigDecimal earnestPrice = price.divide(new BigDecimal(3), 2,
					BigDecimal.ROUND_HALF_UP);
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setEarnestPrice(earnestPrice);
			// 运费
			BigDecimal freight = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getFreight();
			// 直播活动id
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).getActivity()
					.setActivityId(activityId);
			// 商品数量
			int productNum = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getProductNum();
			// 计算支付总价 =商品价格X数量+运费
			BigDecimal totalPrice = earnestPrice.multiply(
					new BigDecimal(productNum)).add(freight);
			// 发送数据
			placeorderCall.setData(false, placeorderBean);
			Logger.comment("创建一个C端直播商品订单");
			placeorderCall.callService();
			Logger.debug("createordercall send:"
					+ placeorderCall.getEntityString());
			Logger.debug("createordercall response:"
					+ placeorderCall.getReturnData());
			if (!(placeorderCall.getString("code").equals("200"))) {
				Logger.debug("保存闪购订单失败:" + placeorderCall.getReturnData());
			}
			// 交易号
			int tradingId = placeorderCall.getTradingId();
			// 订单号 这里只创建了一个订单
			int orderId = placeorderCall.getOrderIds().getInt(0);
			orderMap.put("tradingId", tradingId);
			orderMap.put("orderId", orderId);
			orderMap.put("userId", userId);
			orderMap.put("sellerId", sellerId);
			orderMap.put("totalPrice", totalPrice);
			orderMap.put("productId", productId);
			orderMap.put("freight", freight);
			orderMap.put("productName", productName);
			orderMap.put("catalogId", catalogId);
			orderMap.put("activityId", activityId);
			// orderMap.put("ThirdCategoryId", ThirdCategoryId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderMap;
	}

	/**
	 * APP 根据user保存闪购订单
	 * 
	 * @param Map
	 *            user {userid=??,userName=??,phone=??}
	 * @param productName
	 *            下单的商品名称
	 * @return 例如：{CatalogId=cbaaf223-cb52-4d24-b89a-7411a2a85ea4,
	 *         TotalPrice=404.00, OrderId=105257375, SellerId=288484,
	 *         UserId=1113, ProductId=038505f3-b515-4aac-8f0a-f0364d4d378b}
	 */
	@Deprecated
	public Map appSaveOrder(Map user, String productName) {
		Map<String, Comparable> orderMap = new HashMap();
		PlaceOrderReq placeorderBean = this.getDefaultPlaceOrderBean();
		PlaceOrderCall placeorderCall = new PlaceOrderCall();
		try {
			/*** 读取测试数据 ***/
			int userId = (Integer) user.get("userid");
			// String buyUserName = (String) user.get("username");
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			String sellerName = EnvSetup.getData("BuyerName");
			/*** 获取产品信息 ***/
			String productId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductId();
			String catalogId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getCatalogId();
			int activityId = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getActivity()
					.getActivityId();
			BigDecimal price = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0)
					.getEarnestPrice();
			// 买家用户id
			placeorderBean.getUserId();
			// 商家用id
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 运费
			BigDecimal freight = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getFreight();
			// 设置买手
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 商品数量
			int productNum = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getProductNum();
			// 计算支付总价 =商品价格X数量+运费
			BigDecimal totalPrice = price.multiply(new BigDecimal(productNum))
					.add(freight);
			// 发送数据
			placeorderCall.setData(false, placeorderBean);
			Logger.comment("创建一个C端直播商品订单");
			placeorderCall.callService();
			Logger.debug("createordercall send:"
					+ placeorderCall.getEntityString());
			Logger.debug("createordercall response:"
					+ placeorderCall.getReturnData());
			if (!(placeorderCall.getString("code").equals("200"))) {
				Logger.debug("保存闪购订单失败:" + placeorderCall.getReturnData());
			}
			// 交易号
			int tradingId = placeorderCall.getTradingId();
			// 订单号 这里只创建了一个订单
			int orderId = placeorderCall.getOrderIds().getInt(0);
			orderMap.put("tradingId", tradingId);
			orderMap.put("orderId", orderId);
			orderMap.put("userId", userId);
			orderMap.put("sellerId", sellerId);
			orderMap.put("totalPrice", totalPrice);
			orderMap.put("productId", productId);
			orderMap.put("freight", freight);
			orderMap.put("productName", productName);
			orderMap.put("catalogId", catalogId);
			orderMap.put("activityId", activityId);
			// orderMap.put("ThirdCategoryId", ThirdCategoryId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderMap;
	}

	/**
	 * 新的创建c2c订单方法 调用ProductCallService.createC2CProduct 创建直播商品
	 * 
	 * @return orderMap
	 */
	@Deprecated
	public Map appSaveOrder() {
		Map<String, Comparable> orderMap = new HashMap();
		PlaceOrderReq placeorderBean = this.getDefaultPlaceOrderBean();
		PlaceOrderCall placeorderCall = new PlaceOrderCall();
		try {
			/*** 读取测试数据 ***/
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			String buyUserName = EnvSetup.getData("BuyUserName");
			String buyUserPassWord = EnvSetup.getData("BuyUserPassword");
			// 买手信息
			int sellerId = Integer.valueOf(EnvSetup.getData("BuyerId"));
			String sellerName = EnvSetup.getData("BuyerName");
			// 买家用户id
			placeorderBean.setUserId(userId);
			// 商品预付定金价
			BigDecimal earnestPrice = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0)
					.getEarnestPrice();
			String productId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductId();
			String catalogId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getCatalogId();
			String productName = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductName();
			// 设置买手
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 运费
			BigDecimal freight = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getFreight();
			// 商品数量
			int productNum = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getProductNum();
			// 计算支付总价 =商品价格X数量+运费
			BigDecimal totalPrice = earnestPrice.multiply(
					new BigDecimal(productNum)).add(freight);
			// 发送数据
			placeorderCall.setData(false, placeorderBean);
			Logger.comment("创建一个C端直播商品订单");
			placeorderCall.callService();
			Logger.debug("createordercall send:"
					+ placeorderCall.getEntityString());
			Logger.debug("createordercall response:"
					+ placeorderCall.getReturnData());
			if (!(placeorderCall.getString("code").equals("200"))) {
				Logger.debug("保存闪购订单失败:" + placeorderCall.getReturnData());
			}
			// 交易号
			int tradingId = placeorderCall.getTradingId();
			// 订单号 这里只创建了一个订单
			int orderId = placeorderCall.getOrderIds().getInt(0);
			orderMap.put("tradingId", tradingId);
			orderMap.put("orderId", orderId);
			orderMap.put("userId", userId);
			orderMap.put("sellerId", sellerId);
			orderMap.put("totalPrice", totalPrice);
			orderMap.put("productId", productId);
			orderMap.put("freight", freight);
			orderMap.put("productName", productName);
			orderMap.put("catalogId", catalogId);
			//orderMap.put("activityId", activityId);
			// map.put("ThirdCategoryId", ThirdCategoryId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderMap;
	}

	/**
	 * 新的创建订单方法 * @param Map 买家用户信息 user {userid=??,userName=??,phone=??}
	 * 调用ProductCallService.createProduct 创建商品
	 * 
	 * @return map
	 */
	@Deprecated
	public Map createM2cOrder(Map user) {

		Map<String, Object> orderMap = new HashMap<String, Object>();
		try {

			PlaceOrderCall placeorderCall = new PlaceOrderCall();

			int userId;

			if (user.containsKey("userid")) {
				/*** 读取测试数据 ***/
				userId = (Integer) user.get("userid");
			} else if (user.containsKey("userId")) {
				/*** 读取测试数据 ***/
				userId = (Integer) user.get("userId");
			} else {
				throw new Exception("userId没有找到！");
			}

			PlaceOrderReq placeorderBean = this
					.getDefaultPlaceOrderBean(userId);

			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

			// 商品预付定金价
			BigDecimal earnestPrice = new BigDecimal(
					30 + new Random().nextInt(100));

			String productId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductId();
			String catalogId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getCatalogId();
			String productName = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductName();

			// 买家用户id
			placeorderBean.setUserId(userId);
			// 商家用id
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 订单付全款
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.setPaidFull(true);
			// 定金价格
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setEarnestPrice(earnestPrice);
			// 原价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setOriginalPrice(earnestPrice);
			// 成交价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductPrice(earnestPrice);
			// 运费
			BigDecimal freight = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getFreight();
			// 设置为不是活动商品
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setActivity(null);
			// 商品数量
			int productNum = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getProductNum();
			// 计算支付总价 =商品价格X数量+运费
			BigDecimal totalPrice = earnestPrice.multiply(
					new BigDecimal(productNum)).add(freight);
			// 发送数据
			placeorderCall.setData(false, placeorderBean);
			Logger.comment("创建一个M端订单");
			placeorderCall.callService();
			Logger.debug("createordercall send:"
					+ placeorderCall.getEntityString());
			Logger.debug("createordercall response:"
					+ placeorderCall.getReturnData());
			if (!(placeorderCall.getString("code").equals("200"))) {
				Logger.comment("保存M全款支付订单失败:" + placeorderCall.getReturnData());
			}
			// 交易号
			int tradingId = placeorderCall.getTradingId();
			// 订单号 这里只创建了一个订单
			int orderId = placeorderCall.getOrderIds().getInt(0);
			orderMap.put("tradingId", tradingId);
			orderMap.put("orderId", orderId);
			orderMap.put("userId", userId);
			orderMap.put("sellerId", sellerId);
			orderMap.put("totalPrice", totalPrice);
			orderMap.put("productId", productId);
			orderMap.put("freight", freight);
			orderMap.put("productName", productName);
			orderMap.put("catalogId", catalogId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderMap;
	}
	/**
	 * 新的创建订单方法 调用ProductCallService.createProduct 创建商品
	 * 
	 * @return map
	 */
	@Deprecated
	public PlaceOrderResp createM2cOrder() {

		PlaceOrderReq placeorderBean = this.getDefaultPlaceOrderBean();

		/*** 读取测试数据 ***/
		int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
		int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

		// 买家用户id
		placeorderBean.setUserId(userId);
		// 商家用id
		placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
		// 订单付全款
		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.setPaidFull(true);
		// 设置为不是活动商品
		placeorderBean.getOrderGroups().get(0).getOrders().get(0)
				.getOrderItems().get(0).setActivity(null);

		//不使用平台券
		placeorderBean.setYmatouCoupon(null);
		//不使用商家券
		placeorderBean.getOrderGroups().get(0).setSellerCoupon(null);

		return PlaceOrderService.callPlaceOrderService(placeorderBean);

	}
	/**
	 * 重载根据物流方式创建M订单方法 新的创建订单方法 调用ProductCallService.createProduct 创建商品
	 * 
	 * @param type
	 *            LogisticsTypeEnum 物流枚举类型
	 * @return map
	 */
	@Deprecated
	public Map createM2cOrder(
			com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum type) {
		Map<String, Object> productinfoMap = new HashMap<String, Object>();
		Map<String, Object> orderMap = new HashMap<String, Object>();
		try {
			PlaceOrderReq placeorderBean = this.getDefaultPlaceOrderBean();
			PlaceOrderCall placeorderCall = new PlaceOrderCall();
			/*** 读取测试数据 ***/
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			// 商品预付定金价
			BigDecimal earnestPrice = new BigDecimal(
					100 + new Random().nextInt(300));
			// 商品预付定金价
			/*	BigDecimal earnestPrice = placeorderBean.getOrderGroups().get(0)
						.getOrders().get(0).getOrderItems().get(0)
						.getEarnestPrice();*/
			String productId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductId();
			String catalogId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getCatalogId();
			String productName = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductName();
			// 买家用户id
			placeorderBean.setUserId(userId);
			// 商家用id
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 订单付全款
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.setPaidFull(true);
			// 原价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setOriginalPrice(earnestPrice);
			// 成交价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductPrice(earnestPrice);

			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setEarnestPrice(earnestPrice);

			// 设置sellerid
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 物流类型
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setLogisticsType(type);
			// 物流类型为保税发货 设置默认保税取为 杭州保税
			if (type.getCode() == 4 || type.getCode() == 5) {
				placeorderBean
						.getOrderGroups()
						.get(0)
						.getOrders()
						.get(0)
						.getOrderItems()
						.get(0)
						.setBondedArea(
								com.ymatou.iapi.trading.operate.parameter.enums.BondedAreaEnum.HangZhou);
			}
			// 商品数量
			int productNum = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getProductNum();
			// 运费
			BigDecimal freight = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getFreight();
			// 设置为不是活动商品
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setActivity(null);
			// 计算支付总价 =商品价格X数量+运费
			BigDecimal totalPrice = earnestPrice.multiply(
					new BigDecimal(productNum)).add(freight);
			// 发送数据
			placeorderCall.setData(false, placeorderBean);
			Logger.comment("创建一个M端订单");
			placeorderCall.callService();
			Logger.debug("createordercall send:"
					+ placeorderCall.getEntityString());
			Logger.debug("createordercall response:"
					+ placeorderCall.getReturnData());
			if (!(placeorderCall.getString("code").equals("200"))) {
				Logger.comment("保存M全款订单失败:" + placeorderCall.getReturnData());
			}
			// 交易号
			int tradingId = placeorderCall.getTradingId();
			// 订单号 这里只创建了一个订单
			int orderId = placeorderCall.getOrderIds().getInt(0);
			orderMap.put("tradingId", tradingId);
			orderMap.put("orderId", orderId);
			orderMap.put("userId", userId);
			orderMap.put("sellerId", sellerId);
			orderMap.put("totalPrice", totalPrice);
			orderMap.put("productId", productId);
			orderMap.put("freight", freight);
			orderMap.put("productName", productName);
			orderMap.put("catalogId", catalogId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderMap;
	}

	/**
	 * 重载 创建M订单使用平台优惠卷方法 新的创建订单方法 调用ProductCallService.createProduct 创建商品
	 * 
	 * @param couponCode
	 *            优惠卷code
	 * @param couponValue
	 *            优惠卷面额
	 * @return map
	 */
	@Deprecated
	public Map createM2cOrder(String couponCode, BigDecimal couponValue) {
		Map<String, Object> productinfoMap = new HashMap<String, Object>();
		Map<String, Object> orderMap = new HashMap<String, Object>();
		try {
			PlaceOrderReq placeorderBean = this.getDefaultPlaceOrderBean();
			PlaceOrderCall placeorderCall = new PlaceOrderCall();
			/*** 读取测试数据 ***/
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			// 商品预付定金价
			BigDecimal earnestPrice = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0)
					.getEarnestPrice();
			String productId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductId();
			String catalogId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getCatalogId();
			String productName = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductName();

			YmatouCouponVo ymtCoupon = new YmatouCouponVo();
			// 平台优惠券
			ymtCoupon.setApplianceType(YmatouCouponApplianceTypeEnum.ALL);
			ymtCoupon.setCouponCode(couponCode);
			ymtCoupon.setCouponValue(couponValue);

			placeorderBean.setYmatouCoupon(ymtCoupon);
			// 买家用户id
			placeorderBean.setUserId(userId);
			// 商家用id
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 订单付全款
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.setPaidFull(true);
			// 原价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setOriginalPrice(earnestPrice);
			// 设置sellerid
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 成交价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductPrice(earnestPrice);
			// 运费
			BigDecimal freight = BigDecimal.ZERO;

			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.setFreight(freight);
			// 设置为不是活动商品
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setActivity(null);
			// 商品数量
			int productNum = 1;

			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductNum(productNum);

			// 计算支付总价 =商品价格X数量+运费
			BigDecimal totalPrice = earnestPrice.multiply(
					new BigDecimal(productNum)).add(freight);
			// 发送数据
			placeorderCall.setData(false, placeorderBean);
			Logger.comment("创建一个M端全款订单");
			placeorderCall.callService();
			Logger.debug("createordercall send:"
					+ placeorderCall.getEntityString());
			Logger.debug("createordercall response:"
					+ placeorderCall.getReturnData());
			if (!(placeorderCall.getString("code").equals("200"))) {
				Logger.comment("M端全款订单失败:" + placeorderCall.getReturnData());
			}
			// 交易号
			int tradingId = placeorderCall.getTradingId();
			// 订单号 这里只创建了一个订单
			int orderId = placeorderCall.getOrderIds().getInt(0);
			orderMap.put("tradingId", tradingId);
			orderMap.put("orderId", orderId);
			orderMap.put("userId", userId);
			orderMap.put("sellerId", sellerId);
			orderMap.put("totalPrice", totalPrice);
			orderMap.put("productId", productId);
			orderMap.put("freight", freight);
			orderMap.put("productName", productName);
			orderMap.put("catalogId", catalogId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderMap;
	}

	/**
	 * 新的创建多个M2C订单方法 一笔订单 一个交易号，多个订单号
	 * 
	 * @param orderNum
	 *            订单数量
	 * @return map
	 */
	@Deprecated
	public Map createBatchM2cOrder(int orderNum) {

		Map<String, Object> productinfoMap = new HashMap<String, Object>();
		Map<String, Object> orderMap = new HashMap<String, Object>();
		try {
			PlaceOrderReq placeorderBean = this.getDefaultPlaceOrderBean();
			PlaceOrderCall placeorderCall = new PlaceOrderCall();
			/*** 读取测试数据 ***/
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			// 商品预付定金价
			BigDecimal earnestPrice = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0)
					.getEarnestPrice();
			String productId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductId();
			String catalogId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getCatalogId();
			String productName = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductName();

			// 买家用户id
			placeorderBean.setUserId(userId);
			// 商家用id
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 订单付全款
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.setPaidFull(true);
			// 原价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setOriginalPrice(earnestPrice);
			// 设置sellerid
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 成交价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductPrice(earnestPrice);
			// 运费
			BigDecimal freight = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getFreight();
			// 设置为不是活动商品
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setActivity(null);
			// 商品数量
			int productNum = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getProductNum();
			// 复制商品订单信息，创建多个 order
			for (int i = 0; i < orderNum - 1; i++) {
				placeorderBean
						.getOrderGroups()
						.get(0)
						.getOrders()
						.add(placeorderBean.getOrderGroups().get(0).getOrders()
								.get(0));
			}

			// 发送数据
			placeorderCall.setData(false, placeorderBean);
			Logger.comment("创建" + orderNum + "个M端订单");
			placeorderCall.callService();
			Logger.debug("createordercall send:"
					+ placeorderCall.getEntityString());
			Logger.debug("createordercall response:"
					+ placeorderCall.getReturnData());
			if (!(placeorderCall.getString("code").equals("200"))) {
				Logger.comment("保存批量M全款订单失败:" + placeorderCall.getReturnData());
			}
			// 交易号
			int tradingId = placeorderCall.getTradingId();
			// 计算支付总价 =(商品价格X数量+运费)X订单数量
			BigDecimal totalPrice = this
					.getNeedPrePayAmountOfCashBymainOrderId(tradingId);
			// 订单号
			JSONArray orderIds = placeorderCall.getOrderIds();
			orderMap.put("tradingId", tradingId);
			orderMap.put("orderIds", orderIds);
			orderMap.put("userId", userId);
			orderMap.put("sellerId", sellerId);
			// 订单成交价，在外面根据主订单计算
			orderMap.put("totalPrice", totalPrice);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderMap;
	}

	/**
	 * 卖家修改价格
	 * 
	 * @param OrderId
	 * @param SellerId
	 * @return
	 */
	public void changeOrderDiscount(int orderId, int SellerId,
			BigDecimal Discount) {
		try {
			ChangeOrderDiscountBean changeOrderDiscountbean = new ChangeOrderDiscountBean();
			ChangeOrderDiscountCall changeOrderDiscountCall = new ChangeOrderDiscountCall();
			changeOrderDiscountbean.setOrderId(orderId);
			changeOrderDiscountbean.setSellerId(SellerId);
			changeOrderDiscountbean.setDiscount(Discount);
			changeOrderDiscountCall.setData(false, changeOrderDiscountbean);
			Logger.comment("订单:" + orderId + "卖家:" + SellerId + "修改价格："
					+ Discount);
			changeOrderDiscountCall.callService();
			Logger.debug("卖家修改价格send："
					+ changeOrderDiscountCall.getEntityString());
			Logger.debug("卖家修改价格response："
					+ changeOrderDiscountCall.getReturnData());
			if (!(changeOrderDiscountCall.getCode().equals("200"))) {
				Logger.comment("修改价格失败:"
						+ changeOrderDiscountCall.getReturnData());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *订单支付
	 * 
	 * @param userId
	 *            userId
	 * @param tradingId
	 *            交易ID
	 * @param price
	 *            使用余额支付金额，如果为0 ，全部用第三方支付。默认paytype 13 为 app国际支付宝
	 * @return 如果是第三方支付，返回交易新生成的第三方交易号
	 */
	public int orderPayRequest(int userId, BigDecimal price, int tradingId) {
		return orderPayRequest(userId, price, tradingId, "13");
	}

	/**
	 * 订单支付
	 * 
	 * @param userId
	 *            userId
	 * @param tradingId
	 *            交易ID
	 * @param price
	 *            使用余额支付金额，如果为0 ，全部用第三方支付。
	 * @param payType
	 *            第三方支付的类型 paytype 13 为 app国际支付宝，14,15 微信
	 * @return 如果是第三方支付，返回交易新生成的第三方交易号
	 */
	public int orderPayRequest(int userId, BigDecimal price, int tradingId,
			String payType) {
		int newTradingId = 0;
		try {
			// 强制更新交易密码为 abc123
			JUserCallService.UpdateTradingPwd(userId, "abc123");
			com.ymatou.iapi.trading.operate.parameter.req.OrderPayRequestBean orderpayrequestbean = new com.ymatou.iapi.trading.operate.parameter.req.OrderPayRequestBean();
			com.ymatou.iapi.trading.operate.service.OrderPayRequestCall orderpayrequestcall = new com.ymatou.iapi.trading.operate.service.OrderPayRequestCall();
			// 参数
			orderpayrequestbean.setCallBackUrl("www.baidu.com");
			orderpayrequestbean.setUserId(userId);
			orderpayrequestbean.setUseAccountAmount(price);
			orderpayrequestbean.setTradingId(tradingId);
			// String tradingPassword = EnvSetup.getData("TradingPassword");
			orderpayrequestbean.setTradingPwd("abc123");
			orderpayrequestbean.setUserIp("127.0.0.10");
			orderpayrequestbean.setBankId("");

			if (payType.equals("70")) {

				payType = "13";

				//转宝付 70 支付渠道
				orderpayrequestbean.setOptionalPayTypes(Arrays.asList(70));
			}
			orderpayrequestbean.setPayType(payType);
			orderpayrequestbean.setTerminalSource(TerminalSourceEnum.IOS);
			orderpayrequestbean.setUsePlatform(PlatformEnum.Shangou_WAP
					.getValue());

			orderpayrequestbean.setParamExt("");
			orderpayrequestbean.setMemo("auto自动化");
			// 发送请求
			orderpayrequestcall.setData(false, orderpayrequestbean);
			Logger.comment("用户:" + userId + "订单支付,交易号:" + tradingId + "付款:"
					+ price);
			orderpayrequestcall.callService();
			newTradingId = orderpayrequestcall.getData().getInt("tradingId");
			if (!(orderpayrequestcall.getCode().equals("200"))) {

				Logger.comment("交易:" + tradingId + ",支付失败,Msg="
						+ orderpayrequestcall.getMsg());

			}
			/*			Logger.info("resultType:"
								+ orderpayrequestcall.getData().getString("resultType"));*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newTradingId;
	}

	/**
	 * 新买家补款
	 * 
	 * @param userId
	 * @param payAmount
	 *            使用余额支付金额，如果为0 ，全部用第三方支付。默认paytype 13 为 app国际支付宝
	 * @param orderId
	 */
	@Deprecated
	public void orderPostPayRequest(int userId, BigDecimal payAmount,
			int orderId) {
		try {
			// 强制更新交易密码为 abc123
			new YmtUsersWapper().updateTradingPwdByUid(userId);
			OrderPostPayRequestBean orderpostpayrequestbean = new OrderPostPayRequestBean();
			OrderPostPayRequestCall orderpostpayrequestcall = new OrderPostPayRequestCall();
			// 参数
			orderpostpayrequestbean.setUserId(userId);
			orderpostpayrequestbean.setOrderId(orderId);
			orderpostpayrequestbean.setTradingPwd("abc123");
			BigDecimal GiftAmount = new BigDecimal(0);
			orderpostpayrequestbean.setUseGiftAmount(GiftAmount);
			orderpostpayrequestbean.setBankId("");
			orderpostpayrequestbean.setUserIp("127.0.0.1");
			orderpostpayrequestbean.setMemo("auto自动化");
			orderpostpayrequestbean.setUseAccountAmount(payAmount);
			orderpostpayrequestbean.setCallBackUrl("http://www.baidu.com");
			orderpostpayrequestbean.setUsePlatform(PlatformEnum.Shangou_APP
					.getValue());
			orderpostpayrequestbean.setParamExt("");
			orderpostpayrequestbean.setPayType("13");
			// 发送请求
			orderpostpayrequestcall.setData(false, orderpostpayrequestbean);
			Logger.comment("订单:" + orderId + "用户:" + userId + "补款:" + payAmount);
			orderpostpayrequestcall.callService();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新买家补款
	 * 
	 * @param userId
	 * @param payAmount
	 *            使用余额支付金额，如果为0 ，全部用第三方支付。
	 * @param orderId
	 * @param payType
	 *            第三方支付的类型 paytype 13 为 app国际支付宝，14,15 微信
	 */
	@Deprecated
	public void orderPostPayRequest(int userId, BigDecimal payAmount,
			int orderId, String payType) {
		try {
			// 强制更新交易密码为 abc123
			new YmtUsersWapper().updateTradingPwdByUid(userId);
			OrderPostPayRequestBean orderpostpayrequestbean = new OrderPostPayRequestBean();
			OrderPostPayRequestCall orderpostpayrequestcall = new OrderPostPayRequestCall();
			// 参数
			orderpostpayrequestbean.setUserId(userId);
			orderpostpayrequestbean.setOrderId(orderId);
			orderpostpayrequestbean.setTradingPwd("abc123");
			BigDecimal GiftAmount = new BigDecimal(0);
			orderpostpayrequestbean.setUseGiftAmount(GiftAmount);
			orderpostpayrequestbean.setBankId("");
			orderpostpayrequestbean.setUserIp("127.0.0.1");
			orderpostpayrequestbean.setMemo("auto自动化");
			orderpostpayrequestbean.setUseAccountAmount(payAmount);
			orderpostpayrequestbean.setCallBackUrl("http://www.baidu.com");
			orderpostpayrequestbean.setUsePlatform(PlatformEnum.Shangou_APP
					.getValue());
			orderpostpayrequestbean.setParamExt("");
			orderpostpayrequestbean.setPayType(payType);
			// 发送请求
			orderpostpayrequestcall.setData(false, orderpostpayrequestbean);
			Logger.comment("订单:" + orderId + "用户:" + userId + "补款:" + payAmount);
			orderpostpayrequestcall.callService();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 新买家补款
	 * 
	 * @param userId
	 * @param payAmount
	 *            使用余额支付金额，如果为0 ，全部用第三方支付。
	 * @param orderId
	 * @param payType
	 *            第三方支付的类型 paytype 13 为 app国际支付宝，14,15 微信
	 */
	@Deprecated
	public void orderPostPayRequestInJava(int userId, BigDecimal payAmount,
			int orderId, String payType) {
		try {
			// 强制更新交易密码为 abc123
			new YmtUsersWapper().updateTradingPwdByUid(userId);
			com.ymatou.iapi.trading.operate.parameter.req.OrderPostPayRequestBean orderpostpayrequestbean = new com.ymatou.iapi.trading.operate.parameter.req.OrderPostPayRequestBean();
			com.ymatou.iapi.trading.operate.service.OrderPostPayRequestCall orderpostpayrequestcall = new com.ymatou.iapi.trading.operate.service.OrderPostPayRequestCall();
			// 参数
			orderpostpayrequestbean.setUserId(userId);
			orderpostpayrequestbean.setOrderId(orderId);
			orderpostpayrequestbean.setTradingPwd("abc123");
			BigDecimal GiftAmount = new BigDecimal(0);
			orderpostpayrequestbean.setUseGiftAmount(GiftAmount);
			orderpostpayrequestbean.setBankId("");
			orderpostpayrequestbean.setUserIp("127.0.0.1");
			orderpostpayrequestbean.setMemo("auto自动化");
			orderpostpayrequestbean.setUseAccountAmount(payAmount);
			orderpostpayrequestbean.setCallBackUrl("http://www.baidu.com");
			orderpostpayrequestbean.setUsePlatform(PlatformEnum.Shangou_APP
					.getValue());
			orderpostpayrequestbean.setParamExt("");
			orderpostpayrequestbean.setPayType(payType);
			// 发送请求
			orderpostpayrequestcall.setData(false, orderpostpayrequestbean);
			Logger.comment("订单:" + orderId + "用户:" + userId + "补款:" + payAmount);
			orderpostpayrequestcall.callService();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 卖家接单
	 * 
	 * @param OrderId
	 * @param SellerId
	 * @return
	 */
	public void acceptOrder(int orderId, int sellerId) {
		try {
			AcceptOrderBean acceptorderbean = new AcceptOrderBean();
			AcceptOrderCall acceptordercall = new AcceptOrderCall();
			acceptorderbean.setOrderId(orderId);
			acceptorderbean.setSellerId(sellerId);
			acceptordercall.setData(false, acceptorderbean);
			Logger.comment("订单:" + orderId + "卖家:" + sellerId + "接单");
			acceptordercall.callService();
			Logger.debug("卖家接单send：" + acceptordercall.getEntityString());
			Logger.debug("卖家接单response：" + acceptordercall.getReturnData());
			if (!(acceptordercall.getCode().equals("200"))) {
				Logger.comment("接单失败:" + acceptordercall.getReturnData());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 非贝海发货
	 * 
	 * @param OrderId
	 * @param SellerUserId
	 * @return 随机的物流单号
	 */
	public String dispatched(int orderId, int sellerId) {
		String DeliverSummary = TestDataManager.randomStr(10);
		try {
			DispatchedBean dispatchedbean = new DispatchedBean();
			DispatchedCall dispatchedcall = new DispatchedCall();
			dispatchedbean.setBillType(BillTypeEnum.YMTAPI.getValue());
			// 物流单号
			dispatchedbean.setDeliverSummary(DeliverSummary);
			// Logger.debug(DeliverSummary);
			dispatchedbean.setDeliverType("0");
			dispatchedbean.setOrderId(orderId);
			dispatchedbean.setProvider("autotest第三方物流公司");
			dispatchedbean.setSellerUserId(sellerId);

			BigDecimal Weight = new BigDecimal(10);
			dispatchedbean.setWeight(Weight);// 重量
			dispatchedbean.setIsShippedByXlobo(false);
			dispatchedcall.setData(false, dispatchedbean);
			Logger.comment("订单:" + orderId + "卖家:" + sellerId + "发货");
			dispatchedcall.callService();

			if (!dispatchedcall.getCode().equals("200")) {
				Logger.debug("发货失败：" + dispatchedcall.getMsg());

				return null;
			}
			Logger.debug("发货send：" + dispatchedcall.getEntityString());
			Logger.debug("发货response：" + dispatchedcall.getReturnData());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return DeliverSummary;
	}

	/**
	 * 贝海发货
	 * 
	 * @param OrderId
	 * @param SellerUserId
	 * @return 随机的物流单号
	 */
	public String dispatchedByXlobo(int orderId, int sellerId) {
		String DeliverSummary = TestDataManager.randomStr(10);
		try {
			DispatchedBean dispatchedbean = new DispatchedBean();
			DispatchedCall dispatchedcall = new DispatchedCall();
			dispatchedbean.setBillType(BillTypeEnum.YMTAPI.getValue());
			// 物流单号
			dispatchedbean.setDeliverSummary(DeliverSummary);
			// Logger.debug(DeliverSummary);
			dispatchedbean.setDeliverType("0");
			dispatchedbean.setOrderId(orderId);
			dispatchedbean.setProvider("贝海");
			dispatchedbean.setSellerUserId(sellerId);

			BigDecimal Weight = new BigDecimal(10);
			dispatchedbean.setWeight(Weight);// 重量
			dispatchedbean.setIsShippedByXlobo(true);
			dispatchedcall.setData(false, dispatchedbean);
			Logger.comment("订单:" + orderId + "卖家:" + sellerId + "发货");
			dispatchedcall.callService();
			Logger.debug("发货send：" + dispatchedcall.getEntityString());
			Logger.debug("发货response：" + dispatchedcall.getReturnData());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return DeliverSummary;
	}

	/**
	 * 确认收货
	 * 
	 * @param userId
	 * @param orderId
	 * @return
	 */
	public boolean confirmReceive(int userId, int orderId) {
		try {
			ConfirmReceiveBean confirmreceivebean = new ConfirmReceiveBean();
			ConfirmReceiveCall confirmreceivecall = new ConfirmReceiveCall();
			confirmreceivebean.setBuyerId(userId);
			confirmreceivebean.setOrderId(orderId);
			confirmreceivebean.setRemark("自动化测试收货");
			confirmreceivebean.setIgnoreXloboSignedCheck(true);
			// 发送请求
			confirmreceivecall.setData(false, confirmreceivebean);
			Logger.comment("订单:" + orderId + "用户:" + userId + "确认收货");
			confirmreceivecall.callService();
			Logger.debug("确认收货send：" + confirmreceivecall.getEntityString());
			Logger.debug("确认收货response：" + confirmreceivecall.getReturnData());
			if (!confirmreceivecall.getCode().equals("200")) {
				Logger.comment("确认收货失败" + confirmreceivecall.getReturnData());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 卖家申请补款 		业务上已经没有需要补款订单
	 * 
	 * @param OrderId
	 * @param SellerId
	 * @param PayAmount
	 */
	@Deprecated
	public String applyForPostPay(int orderId, int SellerId,
			BigDecimal PayAmount) {
		String PostPayId = null;
		ApplyForPostPayBean afppbean = new ApplyForPostPayBean();
		ApplyForPostPayCall afppcall = new ApplyForPostPayCall();
		try {
			afppbean.setApplyReason("自动化测试补款申请");
			afppbean.setOrderId(orderId);
			afppbean.setPostPayType(1);
			afppbean.setPostPayAmount(PayAmount);
			afppbean.setSellerId(SellerId);
			// 发送请求
			afppcall.setData(false, afppbean);
			Logger.comment("订单:" + orderId + "卖家:" + SellerId + "申请补款:"
					+ PayAmount);
			afppcall.callService();
			Logger.debug("卖家申请补款send:" + afppcall.getEntityString());
			Logger.debug("卖家申请补款response:" + afppcall.getReturnData());
			if (!(afppcall.getCode().equals("200"))) {
				Logger.debug("订单:" + orderId + "补款失败,Msg" + afppcall.getMsg());
			}
			PostPayId = afppcall.getPostPayId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return PostPayId;
	}

	/**
	 * 卖家取消补款
	 * 
	 * @param OrderId
	 * @param SellerId
	 */
	@Deprecated
	public void cancelPostPay(int orderId, int SellerId) {
		CancelPostPayBean cancelpostpaybean = new CancelPostPayBean();
		CancelPostPayCall cancelpostpaycall = new CancelPostPayCall();
		try {
			cancelpostpaybean.setOrderId(orderId);
			cancelpostpaybean.setSellerId(SellerId);
			cancelpostpaycall.setData(false, cancelpostpaybean);
			Logger.comment("订单:" + orderId + "卖家:" + SellerId + "取消补款");
			cancelpostpaycall.callService();
			Logger.debug("卖家取消补款send：" + cancelpostpaycall.getEntityString());
			Logger.debug("卖家取消补款response：" + cancelpostpaycall.getReturnData());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 领用商家优惠券<br>
	 * 创建总数为一张的 每人只能使用一次的 1元优惠券，默认使用商户是配置的SellerId
	 * 
	 * @param UserId
	 * @param CouponBatchCode
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String sendCoupon(int UserId) throws ClientProtocolException,
			IOException {
		return new CouponCallService().receiveCouponInfo(UserId);
	}

	/**
	 * 领用YMT平台优惠券默认链接优惠券<br>
	 * 满100 减
	 * 
	 * @param userId
	 * @param CouponBatchCode
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws InterruptedException
	 */
	public String receivePlatformCoupon(int userId, BigDecimal couponValue)
			throws ClientProtocolException, IOException, InterruptedException {

		Logger.comment(String.format("用户 %s领用YMT平台优惠券,面额 %s", userId,
				couponValue));
		CouponServiceMCallService couponCallService = new CouponServiceMCallService();
		CreateCouponBean createCouponBean = couponCallService
				.setDefaultPlatformCreateCouponBeanForRecieve();
		// 修改为满50
		createCouponBean.getCouponValues().get(0)
				.setOrderMinAmount(new BigDecimal(50));
		createCouponBean.getCouponValues().get(0)
				.setDeductionMaxAmount(couponValue);

		CreateCouponCall createCouponCall = couponCallService
				.createPlatformCoupon(createCouponBean);

		return couponCallService
				.receiveCouponInfo(createCouponCall.getBatchCode(), userId)
				.getUserReceiveResult().getCouponCode();
	}
	/**
	 * 领用YMT平台短码优惠券<br>
	 * 满100 减
	 * 
	 * @param userId
	 * @param CouponBatchCode
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws InterruptedException
	 */
	public String receivePlatformShortCodeCoupon(BigDecimal couponValue)
			throws ClientProtocolException, IOException, InterruptedException {

		CouponServiceMCallService couponCallService = new CouponServiceMCallService();
		CreateCouponBean createCouponBean = couponCallService
				.setDefaultPlatformCreateCouponBeanForRecieve();
		// 修改为满100
		createCouponBean.getCouponValues().get(0)
				.setOrderMinAmount(new BigDecimal(100));

		createCouponBean.getCouponValues().get(0)
				.setDeductionMaxAmount(couponValue);
		CreateCouponCall createCouponCall = couponCallService
				.createPlatformCoupon(createCouponBean);

		String batchcode = createCouponCall.getBatchCode();

		List<YmtCouponBatch> ymtCouponBatchs = new YmtCouponBatchWapper()
				.selectBysBatchCode(batchcode);

		List<YmtCoupon> coupons = new YmtCouponWapper()
				.selectByiBatchId(ymtCouponBatchs.get(0).getiBatchId());

		// 由于创新短码优惠券会进调度任务，存在一定延迟，所以要等待直到相应数据进Ymt_Coupon表
		int flag = 0;
		while (coupons.size() == 0 && flag < 500) {

			Thread.sleep(100);
			coupons = new YmtCouponWapper().selectByiBatchId(ymtCouponBatchs
					.get(0).getiBatchId());
			flag++;
		}

		if (coupons.size() > 0) {
			return coupons.get(0).getsCouponCode();
		} else {
			// 请检查优惠券生成调度器是否出问题
			return null;
		}
	}

	/**
	 * 取消订单
	 * 
	 * @param OrderId
	 * @param userId
	 */
	public void cancelOrder(int orderId, int userId) {
		CancelOrderBean cancelorderbean = new CancelOrderBean();
		CancelOrderCall cancelordercall = new CancelOrderCall();
		try {
			String cancelReason = "自动化测试取消订单";
			cancelorderbean.setCancelReason(cancelReason);
			cancelorderbean.setCancelType(CancelOrderTypeEnum.BuyerCancelOrder
					.getValue());
			cancelorderbean.setOrderId(orderId);
			cancelorderbean.setUserId(userId);
			// 发送请求
			cancelordercall.setData(false, cancelorderbean);
			Logger.comment("取消订单");
			cancelordercall.callService();
			Logger.debug("取消订单send:" + cancelordercall.getEntityString());
			Logger.debug("取消订单response:" + cancelordercall.getReturnData());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 取消订单
	 * 
	 * @param OrderId
	 * @param userId
	 * @param type
	 *            取消类型 1-买家取消 2-卖家取消 3-客服取消 4-系统自动取消
	 */
	public void cancelOrder(int orderId, int userId, CancelOrderTypeEnum type) {
		CancelOrderBean cancelorderbean = new CancelOrderBean();
		CancelOrderCall cancelordercall = new CancelOrderCall();
		try {
			String CancelReason = "自动化测试取消订单";
			cancelorderbean.setCancelReason(CancelReason);
			cancelorderbean.setCancelType(type.getValue());
			cancelorderbean.setOrderId(orderId);
			cancelorderbean.setUserId(userId);
			// 为系统取消
			if (type.getValue() == 4) {
				new DefaultWapper().updateOrderAutoCancelOrderHoursByOrderId(
						0.00, orderId);
			}
			// 发送请求
			cancelordercall.setData(false, cancelorderbean);
			Logger.comment("订单:" + orderId + "," + type + "取消");
			cancelordercall.callService();
			Logger.debug("取消订单send:" + cancelordercall.getEntityString());
			Logger.debug("取消订单response:" + cancelordercall.getReturnData());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * java 重构交易申请退款.
	 * 默认将订单下所有商品申请全款退款
	 * 返回申请退款bean
	 * @param orderId
	 * @return ApplySalesRefundRequestBean 返回退款申请bean
	 */
	public ApplySalesRefundRequestBean applySalesRefundRequestInJavaBean(
			int orderId) {

		ApplySalesRefundRequestBean applysalesrefundrequestBean = new ApplySalesRefundRequestBean();
		try {
			// 订单号
			applysalesrefundrequestBean.setOrderId(orderId);
			// 订单商品明细
			List<Map> ymtOrdersInfoList = new DefaultWapper()
					.selectOrderInfoByOderId(orderId);

			List<SalesRefundInfoBean> salesRefundInfoList = new ArrayList<SalesRefundInfoBean>();

			for (int i = 0; i < ymtOrdersInfoList.size(); i++) {

				String catalogId = (String) ymtOrdersInfoList.get(i).get(
						"sCatalogId");
				int productNum = (Integer) ymtOrdersInfoList.get(i).get(
						"iAmount");

				// 计算商品总价格 商品价格 X 数量+运费
				BigDecimal refoundAmout = ((BigDecimal) ymtOrdersInfoList
						.get(i).get("fProductPrice"))
						.multiply(new BigDecimal(productNum))
						.subtract(
								((BigDecimal) ymtOrdersInfoList.get(i).get(
										"fSellerCouponAmount")))
						.subtract(
								((BigDecimal) ymtOrdersInfoList.get(i).get(
										"fYmtCouponAmount")))
						.subtract(
								(ymtOrdersInfoList.get(i)
										.get("fThirdPartyDiscount")) == null
										? BigDecimal.ZERO
										: (BigDecimal) ymtOrdersInfoList.get(i)
												.get("fThirdPartyDiscount"))
						.add(((BigDecimal) ymtOrdersInfoList.get(i).get(
								"fDiscount")) == null
								? BigDecimal.ZERO
								: (BigDecimal) ymtOrdersInfoList.get(i).get(
										"fDiscount"));

				SalesRefundInfoBean salesRefundInfo = new SalesRefundInfoBean();
				salesRefundInfo.setCatalogId(catalogId);
				salesRefundInfo.setReason("autotest refund");
				salesRefundInfo.setRefundAmount(refoundAmout);
				salesRefundInfo.setRefundBillNo("TH" + i
						+ String.valueOf(orderId));
				salesRefundInfo.setRefundProductNum(productNum);
				salesRefundInfo.setRefundType(1);
				salesRefundInfoList.add(salesRefundInfo);
			}
			applysalesrefundrequestBean
					.setSalesRefundInfoList(salesRefundInfoList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return applysalesrefundrequestBean;
	}
	/**
	 * java 申请退款
	 * 
	 * @param ApplySalesRefundRequestBean 
	 * @return ApplySalesRefundRequestBean 
	 */
	public ApplySalesRefundRequestBean applySalesRefundRequestCall(
			ApplySalesRefundRequestBean applysalesrefundrequestBean) {
		ApplySalesRefundRequestCall applysalesrefundrequestCall = new ApplySalesRefundRequestCall();
		applysalesrefundrequestCall.setData(false, applysalesrefundrequestBean);
		try {
			applysalesrefundrequestCall.callService();
			if (!applysalesrefundrequestCall.getReturnData().equals("ok")) {
				Logger.debug("申请订单号" + applysalesrefundrequestBean.getOrderId()
						+ "退款失败");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return applysalesrefundrequestBean;
	}

	/**
	 * java 申请退款
	 * 申请退该订单下第一件商品全款退款
	 * 
	 * @param orderId
	 */
	public ApplySalesRefundRequestBean applySalesRefundRequestInJava(int orderId) {

		ApplySalesRefundRequestBean applysalesrefundrequestBean = new ApplySalesRefundRequestBean();
		try {
			applysalesrefundrequestBean = this
					.applySalesRefundRequestInJavaBean(orderId);
			//分割第一个list item
			List<SalesRefundInfoBean> newSalesRefundInfoList = applysalesrefundrequestBean
					.getSalesRefundInfoList().subList(0, 1);
			applysalesrefundrequestBean
					.setSalesRefundInfoList(newSalesRefundInfoList);

			applySalesRefundRequestCall(applysalesrefundrequestBean);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return applysalesrefundrequestBean;
	}
	/**
	 * java 重构交易申请退款,退货退款完成接口
	 * 该订单下第一个商品全款退款执行
	 * 
	 * @param orderId
	 */
	public void salesRefundSuccessRequestInJava(int orderId) {
		try {
			ApplySalesRefundRequestBean applysalesrefundrequestBean = this
					.applySalesRefundRequestInJava(orderId);
			this.salesrefundsuccessrequest(applysalesrefundrequestBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * java 重构交易申请退款,退货退款完成接口
	 * 该订单下所有商品全部退款
	 * 
	 * @param orderId
	 */
	public void salesRefundSuccessRequestAllProducts(int orderId) {
		try {
			ApplySalesRefundRequestBean applysalesrefundrequestBean = this
					.applySalesRefundRequestInJavaBean(orderId);
			ApplySalesRefundRequestCall applysalesrefundrequestCall = new ApplySalesRefundRequestCall();
			applysalesrefundrequestCall.setData(false,
					applysalesrefundrequestBean);
			applysalesrefundrequestCall.callService();
			this.salesrefundsuccessrequest(applysalesrefundrequestBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * java 重构交易申请退款,退货退款完成接口
	 * 该订单下所有商品全部退款
	 * 
	 * @param orderId
	 */
	public void salesrefundfailRequestAllProducts(int orderId) {
		try {
			ApplySalesRefundRequestBean applysalesrefundrequestBean = this
					.applySalesRefundRequestInJavaBean(orderId);
			ApplySalesRefundRequestCall applysalesrefundrequestCall = new ApplySalesRefundRequestCall();
			applysalesrefundrequestCall.setData(false,
					applysalesrefundrequestBean);
			applysalesrefundrequestCall.callService();
			this.salesrefundfailrequest(applysalesrefundrequestBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * java 执行退款退货
	 * 
	 * @param applysalesrefundrequestBean
	 */
	public void salesrefundsuccessrequest(
			ApplySalesRefundRequestBean applysalesrefundrequestBean) {

		ApproveRefundBillReq salesrefundsuccessrequestBean = new ApproveRefundBillReq();
		SalesRefundSuccessRequestCall salesrefundsuccessrequestCall = new SalesRefundSuccessRequestCall();
		try {
			int orderId = applysalesrefundrequestBean.getOrderId();
			List<SalesRefundInfoBean> salesRefundInfoList = applysalesrefundrequestBean
					.getSalesRefundInfoList();
			for (SalesRefundInfoBean salesRefundInfo : salesRefundInfoList) {
				String refundBillNo = salesRefundInfo.getRefundBillNo();
				salesrefundsuccessrequestBean.setOrderId(orderId);
				salesrefundsuccessrequestBean.setOperatorInfo("auto refund");
				salesrefundsuccessrequestBean.setRefundBillNo(refundBillNo);
				salesrefundsuccessrequestCall.setData(false,
						salesrefundsuccessrequestBean);
				salesrefundsuccessrequestCall.callService();
				if (!salesrefundsuccessrequestCall.getReturnData().equals("ok")) {
					Logger.debug("执行该订单号" + orderId + "下退款单号" + refundBillNo
							+ "退货退款失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * java 退款拒绝
	 * 
	 * @param applysalesrefundrequestBean
	 */
	public void salesrefundfailrequest(
			ApplySalesRefundRequestBean applysalesrefundrequestBean) {
		RejectRefundBillReq salesrefundfailrequestBean = new RejectRefundBillReq();
		SalesRefundFailRequestCall salesrefundfailrequestCall = new SalesRefundFailRequestCall();
		try {
			int orderId = applysalesrefundrequestBean.getOrderId();
			List<SalesRefundInfoBean> salesRefundInfoList = applysalesrefundrequestBean
					.getSalesRefundInfoList();

			for (SalesRefundInfoBean salesRefundInfo : salesRefundInfoList) {
				String refundBillNo = salesRefundInfo.getRefundBillNo();
				salesrefundfailrequestBean.setOrderId(orderId);
				salesrefundfailrequestBean.setRefundBillNo(refundBillNo);
				salesrefundfailrequestCall.setData(false,
						salesrefundfailrequestBean);
				salesrefundfailrequestCall.callService();
				if (!salesrefundfailrequestCall.getReturnData().equals("ok")) {
					Logger.debug("拒绝订单号" + orderId + "下退款单号" + refundBillNo
							+ "退货退款失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 卖家延迟发货
	 * 
	 * @param orderId
	 * @param sellerId
	 * @param delayDay
	 *            延迟几天
	 */
	public void sellerDelayReceiveTime(int orderId, int sellerId, int delayDay) {
		DelayReceiveReqBean delayReceiveReqBean = new DelayReceiveReqBean();
		DelayReceiveCall delayReceiveCall = new DelayReceiveCall();
		try {

			delayReceiveReqBean.setDelayDay(delayDay);
			delayReceiveReqBean.setOrderId(orderId);
			delayReceiveReqBean.setOperateUserId(sellerId);
			delayReceiveReqBean.setRemark("自动化测试延长信息");
			delayReceiveReqBean.setOperateUserType(0);

			// 发送请求
			delayReceiveCall.setData(false, delayReceiveReqBean);
			Logger.comment("订单:" + orderId + "用户:" + sellerId + "延迟:"
					+ delayDay + "天收货");
			delayReceiveCall.callService();
			Logger.debug("买家延迟收货 send:" + delayReceiveCall.getEntityString());
			Logger.debug("买家延迟收货 response:" + delayReceiveCall.getReturnData());
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	/**
	 * 买家延迟收货
	 * 
	 * @param orderId
	 * @param userId
	 * @param delayDay
	 *            延迟几天
	 */
	public void buyerDelayReceiveTime(int orderId, int userId, int delayDay) {
		DelayReceiveReqBean delayReceiveReqBean = new DelayReceiveReqBean();
		DelayReceiveCall delayReceiveCall = new DelayReceiveCall();
		try {

			delayReceiveReqBean.setDelayDay(delayDay);
			delayReceiveReqBean.setOrderId(orderId);
			delayReceiveReqBean.setOperateUserId(userId);
			delayReceiveReqBean.setRemark("自动化测试延长信息");
			delayReceiveReqBean.setOperateUserType(1);

			// 发送请求
			delayReceiveCall.setData(false, delayReceiveReqBean);
			Logger.comment("订单:" + orderId + "用户:" + userId + "延迟:" + delayDay
					+ "天收货");
			delayReceiveCall.callService();
			Logger.debug("买家延迟收货 send:" + delayReceiveCall.getEntityString());
			Logger.debug("买家延迟收货 response:" + delayReceiveCall.getReturnData());
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	/**
	 * 批量取消订单
	 * 
	 * @param userid
	 *            买家 or 卖家
	 * @param ArrayList
	 *            <Integer> OrderIdList
	 * @param type
	 *            取消类型 1-买家取消 2-卖家取消 3-客服取消 4-系统自动取消
	 */
	public void batchCancelOrders(int userid, ArrayList<Integer> orderIdList,
			CancelOrderTypeEnum type) {
		BatchCancelOrderBean batchcancelorderbean = new BatchCancelOrderBean();
		BatchCancelOrderCall batchcancelordercall = new BatchCancelOrderCall();
		try {
			batchcancelorderbean.setCancelReason("自动化批量取消订单");
			batchcancelorderbean.setUserId(userid);
			batchcancelorderbean.setOrderIdList(orderIdList);
			batchcancelorderbean.setCancelType(type);
			// 发送请求
			batchcancelordercall.setData(false, batchcancelorderbean);
			batchcancelordercall.callService();
			Logger.debug("批量取消订单 send:"
					+ batchcancelordercall.getEntityString());
			Logger.debug("批量取消订单 response:"
					+ batchcancelordercall.getReturnData());
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * 批量接单
	 * 
	 * @param sellerId
	 * @param ArrayList
	 *            <Integer> orderIdList
	 */
	public void batchAcceptOrders(int sellerId, ArrayList<Integer> orderIdList) {
		BatchAcceptOrderBean batchacceptorderbean = new BatchAcceptOrderBean();
		BatchAcceptOrderCall batchacceptordercall = new BatchAcceptOrderCall();
		try {
			// 参数
			batchacceptorderbean.setOrderIds(orderIdList);
			batchacceptorderbean.setSellerId(sellerId);
			// 发送请求
			batchacceptordercall.setData(false, batchacceptorderbean);
			batchacceptordercall.callService();
			Logger.debug("批量接单 send:" + batchacceptordercall.getEntityString());
			Logger.debug("批量接单 response:"
					+ batchacceptordercall.getReturnData());
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * 批量发货
	 * 
	 * @param sellerId
	 * @param ArrayList
	 *            <Integer> orderIdList
	 */
	public void batchDispatched(int sellerId, ArrayList<Integer> orderIdList) {
		BatchDispatchedBean batchdispatchedbean = new BatchDispatchedBean();
		BatchDispatchedCall batchdispatchedcall = new BatchDispatchedCall();
		try {
			ArrayList<DispatchedInfo> dispatchedList = new ArrayList<DispatchedInfo>();
			for (Integer order : orderIdList) {
				// list
				DispatchedInfo info = new DispatchedInfo();
				// 订单类型
				info.setBillType(BillTypeEnum.YMTAPI.getValue());
				// 物流单号
				String deliverSummary = TestDataManager.randomStr(10);
				info.setDeliverSummary(deliverSummary);
				info.setDeliverType("0");
				info.setOrderId(order);
				info.setProvider("洋码头官方合作物流（贝海国际速递）");
				BigDecimal Weight = new BigDecimal(10);
				info.setWeight(Weight);
				dispatchedList.add(info);
			}
			// 准备参数
			batchdispatchedbean.setDispatchedList(dispatchedList);
			batchdispatchedcall.setData(false, batchdispatchedbean);
			batchdispatchedcall.callService();
			Logger.debug("批量发货send:" + batchdispatchedcall.getEntityString());
			Logger.debug("批量发货call response:"
					+ batchdispatchedcall.getReturnData());
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * 卖家批量申请补款
	 * 
	 * @param sellerId
	 * @param ArrayList
	 *            <Integer> orderIdList
	 * @param payAmount
	 *            补款金额
	 * @return postPayIdList
	 */
	public ArrayList<String> batchApplyForPostPay(int sellerId,
			ArrayList<Integer> orderIdList, BigDecimal payAmount) {
		BatchApplyForPostPayBean batchApplyForPostPaybean = new BatchApplyForPostPayBean();
		BatchApplyForPostPayCall batchApplyForPostPaycall = new BatchApplyForPostPayCall();
		ArrayList<String> postPayIdList = new ArrayList<String>();
		try {
			// 循环
			ArrayList<ApplyPostPayInfo> list = new ArrayList<ApplyPostPayInfo>();
			for (Integer orderId : orderIdList) {
				// 补款参数
				ApplyPostPayInfo info = new ApplyPostPayInfo();
				// 补款理由
				info.setApplyReason("自动化测试");
				// 订单ID
				info.setOrderId(orderId);
				// 支付金额
				// BigDecimal payAmount = new BigDecimal(10);
				info.setPostPayAmount(payAmount);
				// 补款类型
				info.setPostPayType(2);
				// 买家ID
				info.setSellerId(sellerId);
				list.add(info);
			}
			batchApplyForPostPaybean.setApplyPostPayInfoList(list);
			// 发送请求
			batchApplyForPostPaycall.setData(false, batchApplyForPostPaybean);
			batchApplyForPostPaycall.callService();
			postPayIdList = batchApplyForPostPaycall.getPostPayId();
			Logger.debug("卖家批量申请补款 send:"
					+ batchApplyForPostPaycall.getEntityString());
			Logger.debug("卖家批量申请补款 response:"
					+ batchApplyForPostPaycall.getReturnData());
		} catch (Exception e) {

			e.printStackTrace();
		}
		return postPayIdList;
	}

	/**
	 * 
	 * 获取java 下单PlaceOrder 接口默认的请求bean
	 * 
	 * 新java 下单，不区分 M,C 商品，是否需要补款看isPaidFull(
	 *
	 */
	public PlaceOrderReq getDefaultPlaceOrderBean() {

		PlaceOrderReq placeorderBean = PlaceOrderService.getDefaultOrderReq();

		return placeorderBean;
	}

	/**
	 * 
	 * 获取java 下单PlaceOrder 接口默认的请求bean
	 * 
	 * 新java 下单，不区分 M,C 商品，是否需要补款看isPaidFull(
	 *
	 */
	public PlaceOrderReq getDefaultPlaceOrderBean(int userId) {

		PlaceOrderReq placeorderBean = PlaceOrderService
				.getDefaultOrderReq(userId);

		return placeorderBean;
	}
	/**
	 * 根据主单号查询所有订单需要支付的定金金额 订单付款（预付款）时，应付的现金金额，C端为支付定金金额，M端为全款
	 * 
	 * @param mainOrderId
	 *            主订单号
	 *
	 */
	public BigDecimal getNeedPrePayAmountOfCashBymainOrderId(int mainOrderId) {
		BigDecimal amout = BigDecimal.ZERO;
		DefaultWapper database = new DefaultWapper();
		BigDecimal totalAmout = BigDecimal.ZERO;
		try {
			// 订单主表
			List<Map> ymtOrderList = database
					.selectOrderByMainOderId(mainOrderId);
			for (Map m : ymtOrderList) {
				// M全款C定金
				BigDecimal fOrderPrice = (BigDecimal) m.get("fOrderPrice");
				// 调整金额
				BigDecimal fOrderDiscount = (BigDecimal) m
						.get("fOrderDiscount");
				// 运费
				BigDecimal fFreight = (BigDecimal) m.get("fFreight");
				// 补款调整金额
				BigDecimal fDiscount = (BigDecimal) m.get("fDiscount");
				// 商家优惠券
				BigDecimal fSellerCouponAmount = (BigDecimal) m
						.get("fSellerCouponAmount");
				// 平台优惠券
				BigDecimal fYmtCouponAmount = (BigDecimal) m
						.get("fYmtCouponAmount");
				// 商家优惠金额
				BigDecimal fSellerPromotionAmount = (BigDecimal) m
						.get("fSellerPromotionAmount");
				// 单个子单应付的定金金额
				amout = fOrderPrice.add(fOrderDiscount).add(fFreight)
						.add(fDiscount).subtract(fSellerCouponAmount)
						.subtract(fYmtCouponAmount)
						.subtract(fSellerPromotionAmount);
				totalAmout = amout.add(totalAmout);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return totalAmout;
	}

	/**
	 * 订单付款（预付款）时，应付的现金金额，C端为支付定金金额，M端为全款
	 * 
	 * @param orderId
	 *            订单号
	 *
	 */
	public BigDecimal getNeedPrePayAmountOfCash(int orderId) {
		BigDecimal amout = BigDecimal.ZERO;
		DefaultWapper database = new DefaultWapper();
		try {
			// 订单主表
			List<Map> ymtOrders = database.selectOrderByOderId(orderId);
			// M全款C定金
			BigDecimal fOrderPrice = (BigDecimal) ymtOrders.get(0).get(
					"fOrderPrice");
			// 调整金额
			BigDecimal fOrderDiscount = (BigDecimal) ymtOrders.get(0).get(
					"fOrderDiscount");
			// 运费
			BigDecimal fFreight = (BigDecimal) ymtOrders.get(0).get("fFreight");
			// 补款调整金额
			BigDecimal fDiscount = (BigDecimal) ymtOrders.get(0).get(
					"fDiscount");
			// 商家优惠券
			BigDecimal fSellerCouponAmount = (BigDecimal) ymtOrders.get(0).get(
					"fSellerCouponAmount");
			// 平台优惠券
			BigDecimal fYmtCouponAmount = (BigDecimal) ymtOrders.get(0).get(
					"fYmtCouponAmount");
			// 商家优惠金额
			BigDecimal fSellerPromotionAmount = (BigDecimal) ymtOrders.get(0)
					.get("fSellerPromotionAmount");

			amout = fOrderPrice.add(fOrderDiscount).add(fFreight)
					.add(fDiscount).subtract(fSellerCouponAmount)
					.subtract(fYmtCouponAmount)
					.subtract(fSellerPromotionAmount);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return amout.setScale(2);
	}

	/**
	 * 根据订单号,计算该订单.获取订单应付金额(定金+补款)
	 * 
	 * @param orderId
	 *            订单号
	 *
	 */
	public BigDecimal getPayableAmount(int orderId) {
		BigDecimal amout = BigDecimal.ZERO;
		DefaultWapper database = new DefaultWapper();
		try {
			// 订单主表
			List<Map> ymtOrders = database.selectOrderByOderId(orderId);
			// 金额(M全款 C定金+补款)
			BigDecimal fOrderPrice = (BigDecimal) ymtOrders.get(0).get(
					"fTotalPrice");
			// 调整金额
			BigDecimal fOrderDiscount = (BigDecimal) ymtOrders.get(0).get(
					"fOrderDiscount");
			// 运费
			BigDecimal fFreight = (BigDecimal) ymtOrders.get(0).get("fFreight");
			// 补款调整金额
			BigDecimal fDiscount = (BigDecimal) ymtOrders.get(0).get(
					"fDiscount");
			// 商家优惠券
			BigDecimal fSellerCouponAmount = (BigDecimal) ymtOrders.get(0).get(
					"fSellerCouponAmount");
			// 平台优惠券
			BigDecimal fYmtCouponAmount = (BigDecimal) ymtOrders.get(0).get(
					"fYmtCouponAmount");
			// 商家优惠金额
			BigDecimal fSellerPromotionAmount = (BigDecimal) ymtOrders.get(0)
					.get("fSellerPromotionAmount");
			amout = fOrderPrice.add(fOrderDiscount).add(fFreight)
					.add(fDiscount).subtract(fSellerCouponAmount)
					.subtract(fYmtCouponAmount)
					.subtract(fSellerPromotionAmount);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return amout.setScale(2);
	}

	/**
	 * 订单可退款金额（现金部分）
	 * 
	 * @param orderId  订单号
	 *           
	 */
	public BigDecimal getReceiveAmountOfCash(int orderId) {

		BigDecimal amout = BigDecimal.ZERO;
		DefaultWapper database = new DefaultWapper();
		try {
			// 订单资金表
			List<Map> ymtOrderState = database
					.selectOrderStateByOderId(orderId);
			// 订单定金支付的金额
			BigDecimal fPaidAmountOfCash = (BigDecimal) ymtOrderState.get(0)
					.get("fPaidAmountOfCash");
			// 订单补款金额
			BigDecimal fPostPaidAmountOfCash = (BigDecimal) ymtOrderState
					.get(0).get("fPostPaidAmountOfCash");
			// 订单已退款的金额
			BigDecimal fRefundedAmountOfCash = (BigDecimal) ymtOrderState
					.get(0).get("fRefundedAmountOfCash");
			amout = fPaidAmountOfCash.add(fPostPaidAmountOfCash).subtract(
					fRefundedAmountOfCash);

		} catch (Exception e) {
		}
		return amout.setScale(2);
	}

	/**
	 * 获取实付现金金额
	 * 
	 * @param orderId
	 *            订单号
	 *
	 */
	public BigDecimal getRealPayAmountOfCash(int orderId) {
		BigDecimal amount = BigDecimal.ZERO;
		DefaultWapper database = new DefaultWapper();
		try {
			// 订单资金表
			List<Map> ymtOrderState = database
					.selectOrderStateByOderId(orderId);
			// 订单定金支付的金额
			BigDecimal fPaidAmountOfCash = (BigDecimal) ymtOrderState.get(0)
					.get("fPaidAmountOfCash");
			// 订单补款金额
			BigDecimal fPostPaidAmountOfCash = (BigDecimal) ymtOrderState
					.get(0).get("fPostPaidAmountOfCash");
			amount = fPaidAmountOfCash.add(fPostPaidAmountOfCash);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return amount.setScale(2);
	}

	/**
	 * 批量创建C2C订单
	 * 
	 * @param orderNum 创建订单的数量
	 * @return
	 */
	public Map createBatchC2COrder(int orderNum) {
		Map<String, Object> productinfoMap = new HashMap<String, Object>();
		Map<String, Object> orderMap = new HashMap<String, Object>();
		try {
			PlaceOrderReq placeorderBean = this.getDefaultPlaceOrderBean();
			PlaceOrderCall placeorderCall = new PlaceOrderCall();
			/*** 读取测试数据 ***/
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			// 商品预付定金价
			BigDecimal earnestPrice = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0)
					.getEarnestPrice();
			String productId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductId();
			String catalogId = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getCatalogId();
			String productName = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getOrderItems().get(0).getProductName();
			int activityId = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getActivity()
					.getActivityId();
			BigDecimal originalPrice = earnestPrice.add(new BigDecimal(50));
			// 买家用户id
			placeorderBean.setUserId(userId);
			// 商家用id
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 定金+尾款
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.setPaidFull(false);
			// 原价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setOriginalPrice(originalPrice);
			// 设置sellerid
			placeorderBean.getOrderGroups().get(0).setSellerId(sellerId);
			// 成交价
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setProductPrice(originalPrice);
			// 运费
			BigDecimal freight = placeorderBean.getOrderGroups().get(0)
					.getOrders().get(0).getFreight();
			// 设置为不是活动商品
			placeorderBean.getOrderGroups().get(0).getOrders().get(0)
					.getOrderItems().get(0).setActivity(null);
			// 商品数量
			int productNum = placeorderBean.getOrderGroups().get(0).getOrders()
					.get(0).getOrderItems().get(0).getProductNum();
			// 复制商品订单信息，创建多个 order
			for (int i = 0; i < orderNum - 1; i++) {
				placeorderBean
						.getOrderGroups()
						.get(0)
						.getOrders()
						.add(placeorderBean.getOrderGroups().get(0).getOrders()
								.get(0));
			}
			// 计算支付总价 =(商品价格X数量+运费)X订单数量
			BigDecimal totalPrice = (earnestPrice.multiply(new BigDecimal(
					productNum)).add(freight))
					.multiply(new BigDecimal(orderNum));
			// 发送数据
			placeorderCall.setData(false, placeorderBean);
			Logger.comment("创建" + orderNum + "个M端订单");
			placeorderCall.callService();
			Logger.debug("createordercall send:"
					+ placeorderCall.getEntityString());
			Logger.debug("createordercall response:"
					+ placeorderCall.getReturnData());
			if (!(placeorderCall.getString("code").equals("200"))) {
				Logger.comment("保存批量M全款订单失败:" + placeorderCall.getReturnData());
			}
			// 交易号
			int tradingId = placeorderCall.getTradingId();
			// 订单号
			JSONArray orderIds = placeorderCall.getOrderIds();
			orderMap.put("tradingId", tradingId);
			orderMap.put("orderIds", orderIds);
			orderMap.put("userId", userId);
			orderMap.put("sellerId", sellerId);
			// 订单成交价，在外面根据主订单计算
			// orderMap.put("totalPrice", totalPrice);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderMap;
	}

	/**
	 * 买家删除订单
	 * 
	 * @param orderId
	 *            订单号
	 * @param userId
	 *            买家
	 * @param delete
	 *            true:删除订单, false:恢复删除的订单
	 */
	public void salesMarkOrderDeleted(int orderId, int userId, boolean delete) {
		MarkOrderDeletedBean markorderdeletedBean = new MarkOrderDeletedBean();
		MarkOrderDeletedCall markorderdeletedCall = new MarkOrderDeletedCall();
		try {
			markorderdeletedBean.setIsDelete(delete);
			markorderdeletedBean.setOrderId(orderId);
			markorderdeletedBean.setUserId(userId);
			markorderdeletedCall.setData(markorderdeletedBean);
			markorderdeletedCall.callService();
			if (!markorderdeletedCall.getSuccess().equals("true")) {
				Logger.debug("订单号" + orderId + "删除失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 客服锁定订单
	 * 
	 * @param orderId
	 *            订单号
	 * @param  status 1,锁定 0 解锁          
	 */
	public void markOrderLock(int orderId, int status) {

		MarkOrderLockReq markorder = new MarkOrderLockReq();
		MarkOrderLockCall markorderCall = new MarkOrderLockCall();
		try {
			markorder.setLockStatus(status);
			markorder.setOrderId(orderId);
			markorderCall.setData(markorder);
			markorderCall.callService();
			if (!markorderCall.getSuccess()) {
				Logger.debug("订单号" + orderId + "锁定失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {

		OrderCallService order = new OrderCallService();

		//		Map map = order.createM2cOrder();
		//		int orderId = (Integer) map.get("orderId");
		//		int sellerId = (Integer) map.get("sellerId");
		//		int userId = (Integer) map.get("userId");
		//		int tradingId = (Integer) map.get("tradingId");
		//		BigDecimal totalPrice =  placeOrderResp.getPayAmount();// 支付金额
		///*		// 买家付款
		//		int thirdTradingId = order.orderPayRequest(userId,
		//				totalPrice, tradingId);
		//		
		//		order.applySalesRefundRequestInJava(orderId);*/
		//		

		//order.dispatchedByXlobo(112475351, 3383);

		try {
			JUserCallService.UpdateTradingPwd(3383, "abc123");
			//JUserCallService.UpdateTradingPwd(20320997, "abc123");
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			order.receivePlatformCoupon(20238699, new BigDecimal(1));
			//			order.receivePlatformCoupon(20238699, new BigDecimal(1));
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
